package com.talkyun.openx.interceptor;

import com.talkyun.openx.server.core.Interceptor;
import com.talkyun.openx.server.core.ServiceContext;
import com.talkyun.openx.server.core.ServiceRequest;
import com.talkyun.openx.server.core.ServiceResponse;

public abstract class AbstractMatcherInterceptor extends AbstractSpringAntMatcher implements Interceptor {
    public String FLAG_SR = "$SR";
    public String FLAG_SP = "$SP";

    @Override
    public final void onMessageIn(ServiceContext ctx, ServiceRequest sr) {
        ctx.putIfNull(FLAG_SR, sr);

        if (this.isMatched(ctx)) {
            this.doMessageIn(sr);
        }
    }

    @Override
    public final void onMessageOut(ServiceContext ctx, ServiceResponse sp) {
        ctx.putIfNull(FLAG_SP, sp);

        if (this.isMatched(ctx)) {
            doMessageOut(sp);
        }
    }

    @Override
    public final void onException(ServiceContext ctx, Throwable t) {
        if (this.isMatched(ctx)) {
            doException(t);
        }
    }

    protected boolean isMatched(ServiceContext ctx) {
        ServiceRequest sr = (ServiceRequest) ctx.getValue(FLAG_SR);
        String mapping = sr.getMapping();
        String method = sr.getMethod();
        String uri = mapping + "/" + method;

        String pkg = uri.replaceAll("/",".");
        return super.isMatched(pkg);
    }

    protected void doMessageIn(ServiceRequest sr) {
        // impl by sub-class
    }

    protected void doMessageOut(ServiceResponse sp) {
        // impl by sub-class
    }

    protected void doException(Throwable t) {
        // impl by sub-class
    }
}